package com.rocky.ssm.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Author Meice
 * @Date 2017年8月10日
 */
public class BaseDao {
	Connection conn = null;
	PreparedStatement ps = null;
	ResultSet rs = null;
	//静态语句块加载 驱动
	static{
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	//定义获取连接方法getConn()
	public Connection getConn() {
		String url = "jdbc:mysql://192.168.35.149:3306/rems";
		String user = "root";
		String password = "root";
		try {
			conn = DriverManager.getConnection(url, user, password);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("恭喜你，连接成功！");
		return conn;
	}
	//定义释放资源方法closeConnection()
	public void closeConnection(ResultSet rs,PreparedStatement ps, Connection conn) {
		try {
			if(rs != null) rs.close();
			if(ps != null) ps.close();
			if(conn != null) conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	//定义增删改方法executeUpdate()
	public int executeUpdate(String sql,Object[] params) {
		int result = 0;
		conn = this.getConn();
		try {
			ps = conn.prepareStatement(sql);
			//遍历参数数组，为其赋值
			if(params != null && params.length>0) {
				for(int i=0;i<params.length;i++){
					ps.setObject((i+1),params[i]);	
				}			
			}
		result =ps.executeUpdate();
		//验证下是否操作成功！
		if(result>0){
			System.out.println("恭喜！增删改之一操作成功！");
			
		}else {
			System.out.println("遗憾。增删改之一操作失败...");
		}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			//没有rs，设置为null
			this.closeConnection(null, ps, conn);
		}
		return result;
	}
	
	
	public static void main(String[] args) {
		new BaseDao().getConn();
	}
	
}
